import commonActions from 'actions/common'
import { saveData } from 'utils'
import { message } from 'antd'

export default {
  state: {
    areaResList: [],
    auth: []
  }, // initial state
  reducers: {
    _logout (state) {
      return state
    },
    save (state, payload) {
      return saveData(state, payload)
    }
  },
  effects: dispatch => ({
    // 登出
    async deleteLogout (params) {
      const res = await commonActions.logout({
        token: localStorage.getItem('token')
      })
      if (res.success) {
        // localStorage.setItem('token', null)
        // localStorage.setItem('nickname', null)
        localStorage.removeItem('token')
        localStorage.removeItem('nickname')
        location.href = '/login'
      } else {
        message.error(res.msg)
      }
    },
    // 登陆
    async login (params) {
      const res = await commonActions.login(params)
      if (res.success) {
        localStorage.setItem('token', res.data.userToken)
        localStorage.setItem('nickname', res.data.name)
        localStorage.setItem('loginData', JSON.stringify(res.data))
        localStorage.setItem('userId', res.data.userId)
        localStorage.setItem('avatar', res.data.avatar)
        location.href = '/'
      } else {
        message.error(res.msg)
      }
    },
    // 获取城市级联数据
    async getAreaList (params) {
      const res = await commonActions.getAreaList(params)
      this.save({
        areaResList: res.data.rootList
      })
    },
    async getAuthCode () {
      const res = await commonActions.getAuthCode()
      this.save({
        auth: res.data
      })
    }
  })
}
